package com.by.datasource.dynamictablename;

import com.baomidou.mybatisplus.annotation.TableName;
import com.by.toolkit.consts.GlobalConst;
import com.by.toolkit.utils.ThreadLocalUtil;
import com.by.toolkitspring.customizeannotation.AbstractByAnnotationContext;
import com.by.toolkitspring.customizeannotation.ByAnnotationProcessor;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class DyTNContext implements AbstractByAnnotationContext<DyTN> {

    private static final Set<Class<?>> CLASSES = Sets.newHashSet();

    private static final Map<String, Integer> TABLE_DYNAMIC_TABLE_NAME_MAP = Maps.newHashMap();

    @Override
    public void receiveContext(List<ByAnnotationProcessor.CustomizeAnnotationInfo> infos) {
        if (CollectionUtils.isEmpty(infos)) {
            return;
        }
        CLASSES.addAll(infos.stream()
                .map(ByAnnotationProcessor.CustomizeAnnotationInfo::getBeanClass)
                .collect(Collectors.toSet()));

        infos.forEach(info -> {
            TableName tableName = info.getBeanClass().getAnnotation(TableName.class);
            DyTN dyTN = info.getBeanClass().getAnnotation(DyTN.class);
            if (Objects.isNull(dyTN) || Objects.isNull(tableName)) {
                return;
            }
            TABLE_DYNAMIC_TABLE_NAME_MAP.put(tableName.value(), dyTN.value());
        });
    }

    public boolean dynamicTableName(String tableName) {
        return TABLE_DYNAMIC_TABLE_NAME_MAP.containsKey(tableName);
    }

    public Integer dynamicTableNameAlgorithm(String tableName) {
        return TABLE_DYNAMIC_TABLE_NAME_MAP.get(tableName);
    }

    public void disabled() {
        ThreadLocalUtil.put("DISABLED_DYNAMIC_TABLE_NAME", GlobalConst.ZERO_STR, false);
    }

    public boolean disabledFlag() {
        return Objects.nonNull(ThreadLocalUtil.getString("DISABLED_DYNAMIC_TABLE_NAME"));
    }

    public void clear() {
        ThreadLocalUtil.removeKey("DISABLED_DYNAMIC_TABLE_NAME", false);
    }

}
